//
//  WMMineController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/5.
//

import UIKit


class WMMineController: WMBaseViewController {
    
    @IBOutlet weak var headImageView: UIImageView!
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var loginTipsLabel: UILabel!
    @IBOutlet weak var userNameTopConstant: NSLayoutConstraint! //用户名称距离顶部高度 登录28.8 未登录15
    
    @IBOutlet weak var vipTimeLabel: UILabel!
    @IBOutlet weak var unlockBtn: UIButton! //解锁功能

    @IBOutlet weak var tableView: UITableView!
    
    var expireDate: String = ""
    var hasLogin: Bool = false //是否登录
    var dataList: [[String: Any]] = []
    var isMember: Bool = false
    var alertView = KBAlertView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        isNavigationBarHidden = true
        self.tableView.register(UINib(nibName: "WMMineListCell", bundle: nil), forCellReuseIdentifier: "WMMineListCell")
        updatePageUI()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updatePageUI()
        requestWithDynamicList()
    }

    //MARK: 按钮点击事件
    //解锁功能按钮点击事件
    @IBAction func unlockBtnClickAction(_ sender: Any) {
        let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
        navigationController?.pushViewController(vc, animated: true)
    }
    //未登录手势按钮点击事件
    @IBAction func unLoginTapGesture(_ sender: Any) {
        if(self.hasLogin == false){
            let vc = WMLoginViewController(nibName: "WMLoginViewController", bundle: nil)
            navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    //更新页面UI
    func updatePageUI(){
        hasLogin = (UserDefaults.standard.value(forKey: UserDefaultsKey.loginUserId) as? Int).or(0) > 0
        vipTimeLabel.text = isMember ? "会员截止\(self.expireDate)" : ""
        unlockBtn.isHidden = isMember
        if(self.hasLogin == true){ //已登录
            self.loginTipsLabel.isHidden = true
            self.userNameTopConstant.constant = 28.5
            self.userNameLabel.text = (UserDefaults.standard.value(forKey: UserDefaultsKey.loginUserName) as? String).or("")
            self.headImageView.setImageUrl((UserDefaults.standard.value(forKey: UserDefaultsKey.loginUserAvatar) as? String).or(""), placeholder: UIImage(named: "mine_head_nor"))
        }else{ //未登录
            self.loginTipsLabel.isHidden = false
            self.userNameLabel.text = "未登录"
            self.userNameTopConstant.constant = 15
            self.headImageView.image = UIImage(named: "mine_head_nor")
        }
        self.tableView.reloadData()
    }
    
    //页面功能模块列表
    func requestWithDynamicList(){
        WMAgentApi.shared.requestApi(ApiEnum.myFuncList) { res in
            let data = res["data"] as? [String: Any]
            let list = data?["dynamicList"] as? [[String: Any]]
            let code: String = res["code"] as! String
            if (code == "200" || code == "0"){
                self.dataList = list ?? []
                self.isMember = data?["memberStatus"] as? Int == 1
                UserDefaults.standard.setValue(self.isMember ? 1 : 0, forKey: UserDefaultsKey.isMember)
                self.expireDate = (data?["expireDate"] as? String) ?? ""
                Async.main {
                    self.updatePageUI()
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    //注销账号
    func requestWithLogOut(){
        showHUD()
        WMAgentApi.shared.requestApi(ApiEnum.logout) { res in
            let code: String = res["code"] as! String
            if (code == "200" || code == "0") {
                KBToast.show("账号注销成功")
                UserDefaults.standard.setValue(0, forKey: UserDefaultsKey.loginUserId)
                UserDefaults.standard.setValue("", forKey: UserDefaultsKey.loginUserToken)
                Async.main {
                    self.requestWithDynamicList()
                }
            }
        }
        // 重新获取一键登录的code
        NTESQuickLoginManager.sharedInstance().getPhoneNumberCompletion { resultDic in
            let resultCode = resultDic["resultCode"] as? String ?? ""
            let token = resultDic["token"] as? String ?? ""
            UserDefaults.standard.setValue(token, forKey: UserDefaultsKey.oneKeyPhoneTokenKey)
            UserDefaults.standard.setValue(resultCode, forKey: UserDefaultsKey.oneKeyPhoneCodeKey)
            UserDefaults.standard.synchronize()
        }
    }
    
}


extension WMMineController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if(section == 0){
            return 2
        }else if (section == 1){
            return 1 + self.dataList.count
        }else{
            return 2 + (hasLogin ? 2 : 0)
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "WMMineListCell") as! WMMineListCell
        if indexPath.section == 0{
            cell.titleLabel.text = ["问题反馈", "用户许可协议"][indexPath.row]
            cell.iconImageView.image = UIImage(named: ["mine_problem_feedback_icon", "mine_user_license_agreement_icon"][indexPath.row])
            if(indexPath.row == 1){
                cell.lineView.isHidden = true
            }else{
                cell.lineView.isHidden = false
            }
        }else  if indexPath.section == 1 {
            if(indexPath.row == self.dataList.count){
                cell.titleLabel.text = "用户隐私"
                cell.lineView.isHidden = true
                cell.iconImageView.image = UIImage(named: "mine_user_privacy_icon")
            }else{
                cell.lineView.isHidden = false
                cell.titleLabel.text = dataList[indexPath.row]["useWord"] as? String ?? ""
                cell.iconImageView.setImageUrl(dataList[indexPath.row]["icon"] as? String ?? "")
            }
        }else{
            cell.titleLabel.text = ["分享", "历史记录", "退出登录", "注销账号"][indexPath.row]
            cell.iconImageView.image = UIImage(named: ["mine_share_icon", "mine_history_icon", "mine_user_privacy_icon", "mine_user_privacy_icon"][indexPath.row])
            if(hasLogin == true){
                if(indexPath.row == 3){
                    cell.lineView.isHidden = true
                }else{
                    cell.lineView.isHidden = false
                }
            }else{
                if(indexPath.row == 1){
                    cell.lineView.isHidden = true
                }else{
                    cell.lineView.isHidden = false
                }
            }
        }
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 10))
        view.backgroundColor = UIColor(valueRGB: 0xf6f6f9, alpha: 1.0)
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if(indexPath.section == 0){
            if(indexPath.row == 0){ //跳转到问题反馈
                let vc = WMFeedBackViewController(nibName: "WMFeedBackViewController", bundle: nil)
                navigationController?.pushViewController(vc, animated: true)
            }else{
                let web = WebViewController()
                web.modalPresentationStyle = .fullScreen
                web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.userProtocol) as? String ?? ""
                present(web, animated: true)
            }
        }else if(indexPath.section == 1){
            if(indexPath.row == self.dataList.count){
                let web = WebViewController()
                web.modalPresentationStyle = .fullScreen
                web.url = UserDefaults.standard.value(forKey: UserDefaultsKey.sercurityProtocol) as? String ?? ""
                present(web, animated: true)
            }else{
                if let url = dataList[indexPath.row]["wordUrl"] as? String {
                    let web = WebViewController()
                    web.modalPresentationStyle = .fullScreen
                    web.url = url
                    present(web, animated: true)
                }
            }
        }else{
            if(indexPath.row == 0){ //分享
                if !WXApi.isWXAppInstalled() {
                    KBToast.show("暂无可分享的平台")
                    return;
                }
                let shareView = ShareView(frame: UIScreen.main.bounds)
                shareView.shareItemBlock = { index in
                    let message = WXMediaMessage()
                    message.title = UserDefaults.standard.value(forKey: UserDefaultsKey.shareTitle) as? String ?? ""
                    message.description = UserDefaults.standard.value(forKey: UserDefaultsKey.shareContent) as? String ?? ""
                    message.setThumbImage(UIImage(named: "app_icon")!)
                    
                    let webPageObject = WXWebpageObject()
                    webPageObject.webpageUrl = UserDefaults.standard.value(forKey: UserDefaultsKey.shareUrl) as? String ?? ""
                    message.mediaObject = webPageObject
                    
                    let req = SendMessageToWXReq()
                    req.bText = false
                    req.message = message
                    req.scene = Int32(index)
                    WXApi.send(req)
                }
                UIApplication.shared.delegate?.window??.addSubview(shareView)
                requestEventSave(title: "点击分享", mode: "点击分享")
            }else if(indexPath.row == 1){
                let vc = WMRecordViewController(nibName: "WMRecordViewController", bundle: nil)
                navigationController?.pushViewController(vc, animated: true)
            }else if(indexPath.row == 2){ //退出登录
                self.alertView = KBAlertView(title: "", "是否退出登录", cancelButtonTitle: "取消", otherButtonTitle: "退出") {
                    UserDefaults.standard.setValue(0, forKey: UserDefaultsKey.loginUserId)
                    UserDefaults.standard.setValue("", forKey: UserDefaultsKey.loginUserToken)
                    UserDefaults.standard.setValue(0, forKey: UserDefaultsKey.isMember)
                    self.alertView.hideView(isRemove: true)
                    self.updatePageUI()
                    self.requestWithDynamicList()
                    self.tableView.reloadData()
                    
                    // 重新获取一键登录的code
                    NTESQuickLoginManager.sharedInstance().getPhoneNumberCompletion { resultDic in
                        let resultCode = resultDic["resultCode"] as? String ?? ""
                        let token = resultDic["token"] as? String ?? ""
                        UserDefaults.standard.setValue(token, forKey: UserDefaultsKey.oneKeyPhoneTokenKey)
                        UserDefaults.standard.setValue(resultCode, forKey: UserDefaultsKey.oneKeyPhoneCodeKey)
                        UserDefaults.standard.synchronize()
                    }
                } cancelBlock: {
                    self.alertView.hideView(isRemove: true)
                }
                self.alertView.doneButtonTitleColor = UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0)
                self.alertView.showView()
            }else{ //注销账号
                self.alertView = KBAlertView(title: "", "是否注销账号", cancelButtonTitle: "取消", otherButtonTitle: "注销") {
                    self.requestWithLogOut()
                    
                } cancelBlock: {
                    self.alertView.hideView(isRemove: true)
                }
                self.alertView.doneButtonTitleColor = UIColor(valueRGB: UInt(OEMInfo.themeHex), alpha: 1.0)
                self.alertView.showView()
            }
        }
    }
}
